package com.lhy.tool.database.converter;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import com.lhy.tool.database.DbColumnType;
import com.lhy.tool.util.DbTypeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.List;
import java.util.function.Function;

@Component
public class DbColumnTypeConverterHelper {

    private static final String DB_COLUMN_TYPE_MAPPING = "ColumnTypeMapping";

    @Autowired
    MybatisPlusProperties mybatisPlusProperties;

    @Autowired
    DataSourceProperties dataSourceProperties;

    private DbColumnTypeMapping dbColumnTypeMapping;

    @Autowired
    List<DbColumnTypeMapping> dbColumnTypeMappings;

    public DbColumnType converter(String dbColumnType) {
        DbType dbType = JdbcUtils.getDbType(dataSourceProperties.getUrl());
        if (dbColumnTypeMapping == null) {
            dbColumnTypeMapping = getDbColumnTypeMapping(dbType);
        }
        Function<String, DbColumnType> converter = getConverter(dbColumnType);
        return converter.apply(dbColumnType);
    }

    private Function<String, DbColumnType> getConverter(String dbColumnType) {
        return dbColumnTypeMapping.getMappingRules().stream()
                .filter((rule) -> rule.getMatcher().test(dbColumnType))
                .map(ColumnTypeMappingRule::getConverter)
                .findFirst().orElseThrow(() -> new NullPointerException("根据【" + dbColumnType + "】未找到对应转换类"));
    }

    private DbColumnTypeMapping getDbColumnTypeMapping(DbType dbType) {
        return dbColumnTypeMappings.stream()
                .filter(mapping -> DbTypeUtil.isMatch(mapping, DB_COLUMN_TYPE_MAPPING, dbType))
                .findFirst().orElseThrow(() -> new NullPointerException("根据当前dbType：" + dbType + "未找到对应" + DB_COLUMN_TYPE_MAPPING));
    }


}
